package com.example.hblog.module.controller;

import com.example.hblog.Result;
import com.example.hblog.module.pojo.User;
import com.example.hblog.module.service.UserService;
import com.example.hblog.utils.JWTUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

@RestController
@CrossOrigin
@Slf4j
@RequestMapping("api")
public class LoginAndLogoutController {

    @Autowired
    private UserService userService;
    @Autowired
    private HttpServletRequest request;

    /*用户登录*/
    @PostMapping("/login")
    public Result Login(@RequestBody User user){
        try{
            User userlog = userService.userLogin(user);
            String token = JWTUtils.getToken(userlog);
            return new Result(200,"登录成功",token);
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println(e.getMessage());
            return new Result(400,"登录失败,"+e.getMessage(),null);

        }
    }

    /*自动登录判断*/
    @PostMapping("/isAutoLogin")
    public Result isAutoLogin( String loginToken){
        try{
            JWTUtils.verify(loginToken);
            return new Result(200,"自动登录成功",null);
        } catch (Exception e){
            e.printStackTrace();
            return new Result(400,"请登录",null);
        }
    }

    /*获取用户信息*/
    @GetMapping("/userMsg")
    public Map<String,Object> userMsg(String loginToken){
        Map<String,Object> map = new HashMap<>();
        try{
           map = JWTUtils.verify1(loginToken);
           return map;
        } catch (Exception e) {
            e.printStackTrace();
            map.put("state",false);
        }
        return map;
    }

    /*用户注销*/
    @GetMapping("/logout")
    public Result LogOut(){
            try{
                return new Result(200,"注销成功",null);
            } catch (Exception e) {
                e.printStackTrace();
                return new Result(400,"注销失败",null);
            }
    }

}
